var express = require('express');
var router = express.Router();
const { Author } = require('../../models');
const { success, fail } = require('../../utils/response');
const { getAuthor } = require('../../utils/get-data');

router.get('/', async function(req, res, next) {
  try{
    let {page = 1, limit = 10} = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const offset = (page - 1) * limit;
    const {count, rows: authors} = await Author.findAndCountAll({
      offset,
      limit,
    });
    const data = {
      data: authors,
      total: count,
      page,
      limit
    }
    success(res, data, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.get('/:id', async function(req, res, next) {
  try{
    const author = await getAuthor(req, res, next);
    success(res, author, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.post('/', async function(req, res, next) {
  try{
    const {name, introZh, introEn, avatar, link} = req.body;
    const author = await Author.create({name, introZh, introEn, avatar, link});
    success(res, author, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.put('/:id', async function(req, res, next) {
  try{
    const {name, introZh, introEn, avatar, link} = req.body;
    const author = await getAuthor(req, res, next);
    await author.update({ name, introZh, introEn, avatar, link});
    success(res, author, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
router.delete('/:id', async function(req, res, next) {
  try{
    const author = await getAuthor(req, res, next);
    await author.destroy();
    success(res, null, req.t('success'));
  }catch(err){
    fail(res, err, req.t('fail'));
  }
});
module.exports = router;